import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart' as http;

class NovelBookCacheModel extends BaseCacheManager{
  static const key = "libCacheNovelData";

  static NovelBookCacheModel _instance;

  factory NovelBookCacheModel() {
    if (_instance == null) {
      _instance = new NovelBookCacheModel._();
    }
    return _instance;
  }

  NovelBookCacheModel._() : super(key);

  Future<String> getFilePath() async {
    var directory = await getTemporaryDirectory();
    return p.join(directory.path, key);
  }

  Future<File> _getNovelPersistentCacheFile(String url, {Map<String, String> headers}) async {
    FileInfo cacheFile = await getFileFromCache(url);
    if (cacheFile != null&&cacheFile.file!=null) {
      return cacheFile.file;
    }else {
      removeFile(url);
      try {
        debugPrint("=============== 下载文件的地址是${url} =============tys");
        debugPrint("=============== 下载文件的header是${headers} =============tys");
        var download = await webHelper.downloadFile(url, authHeaders: headers);
        print("下载的文件内容是 ${download.file.readAsStringSync()}");
        return download.file;
      } catch (e) {
        return null;
      }
    }
  }

  Future<String> getCacheChapterContent(String chapterLink) async{

    debugPrint("请求最后一步 ${chapterLink.toString()}");
    final response = await http.get(chapterLink,
    );
    return response.body;

//    debugPrint("=========== 请求详细内容 ===========");
//
//    File targetFile = await _getNovelPersistentCacheFile("http://book-98nice.oss-cn-hangzhou.aliyuncs.com/DSYL00/E427D54B9D3674455296705C2BDBF8F1/8CD06AEBD023BAEA715F703714A92616");
//
//    if (targetFile == null) {
//      return null;
//    } else {
//      Uint8List bytes = await targetFile.readAsBytes();
//      return utf8.decode(bytes, allowMalformed: true);
//    }
  }

}